﻿	using COC.Debug;
	using UnityEngine;
	using System.Collections;
	using System.Collections.Generic;
	using COC.CEvent;
	using COC.Content;
	using COC.Content.Task;
	using COC.UIAction;
	using System.IO;
	using System;
	using System.Text;
	using System.Threading;
	using COC.Web;
	using COC.Tool;
	using COC.Exception;
	namespace COC.Test
	{
		public class ExampleParallelTasksManaged : MonoBehaviour
		{
			int i; 
			bool variableThatCouldHaveBeenUseful;
			ParallelTaskCollection pt;
			SerialTaskCollection st;
			ResourceManager rm = ResourceManager.getInstance ();
			LoaderManager lm;
			ZipTools zipTools;
			Thread mainThread;
			bool isActive;
			List<Thread> stacks = new List<Thread> ();
			public UISlider progressbar;
			public UILabel progressbar_info;

			void Awake ()
			{

				if (progressbar == null) {
					GameObject go = GameObject.FindGameObjectWithTag ("Login_progressbar");
					UISlider slider = go.GetComponent<UISlider> ();
					UILabel _info = GameObject.FindGameObjectWithTag ("Login_progressbar_info").GetComponent<UILabel> ();
					if (slider != null) {
						progressbar = slider;
					}
					if (_info != null)
						progressbar_info = _info;
				}
			}
			// Use this for initialization
			void Start ()
			{


				//FileTools.CreateDirectorys("1/2/3/4/5",Application.dataPath);
                DebugTool.Log(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "/" + "COCDemo" + "/Logs");
				lm = this.gameObject.AddComponent<LoaderManager> ();
				zipTools = this.gameObject.AddComponent<ZipTools> ();
				StartCoroutine ("StartC");
				GameObject.Find ("mainFrame").GetComponent<MainTask> ().setActive (true);
				//Debug.Log("AAA");
				pt = new ParallelTaskCollection ();
				st = new SerialTaskCollection ();

				st.description = "Downloading resource";
				st.Add (Print ("s1"));
				st.Add (Print ("s2"));
				//st.Add (DoSomethingAsynchonously ());
				st.Add (Print ("s3"));
				st.Add (Print ("s4"));

				pt.Add (Print ("1"));
				//pt.Add (Print ("2"));
				//pt.Add (WWWTest ("www.google.com"));
				pt.Add (rm.DownloadBundlesInfos ("bundlesInfo.txt"));
				pt.Add (rm.SaveBundlesInfo ("www", "bundlesInfo.txt", JSON));
				//pt.Add ( WWWModel("file://D:/Users/Calanoric/Documents/CoCDemo/AssetBundles/level1.unity3d","Human_0", 3,LoadResourceType.GAMEOBJECT,null));

				///string BundleURL, string Path, LoadResourceType Type, string AssetName,bool LoadAll,
				/// List<CTuple<string,string,int>> Params, bool WhetherGameObject,
				/// int Level, string SceneName, int Version
				 

				pt.Add (lm.LoadAsset ("file://D:/Users/Calanoric/Documents/CoCDemo/AssetBundles/level1.unity3d", "", LoadResourceType.DEFAULT, "Human_0", false, null, true, 0, "", 5));

				pt.Add (Print ("3"));
				//pt.Add (Print ("4"));
				pt.Add (st);
				//pt.Add (Print ("5"));
				//pt.Add (Print ("6"));
				//pt.Add (Print ("7"));

				TaskRunner.Instance.RunManaged (pt);
				StartCoroutine ("ShowProgress");
				pt.onComplete += () => {
                    DebugTool.Log(" st.progress=" + st.progress * 100 + "% ;" + "Finished:=" + ((pt.progress) * 100) + "%");
					StopCoroutine ("ShowProgress");
					isFinished = true;
					if (isFinished) {
						if (progressbar_info != null)
							progressbar_info.text = "";
						if (progressbar != null) {
							NGUITools.SetActive (progressbar.gameObject, false);
						}
					}
				};
				//{
				//};

			}

			bool isFinished;

			IEnumerator ShowProgress ()
			{
				while (true) {
					{
						UISlider slider = progressbar;
						slider.value = pt.progress;
						progressbar_info.text = st.description;
					}

                    DebugTool.Log("st.progress = " + st.progress * 100 + "% ;" + "pt.Progress =" + pt.progress * 100 + "%");
					yield return null;
				}

			}

			public void  Finished ()
			{
			}

			IEnumerator StartC ()
			{
                DebugTool.Log("asdfghjkl");
				//main frame in Game UI Thread
				GameObject mainFrame = GameObject.Find ("mainFrame");

				if (mainFrame == null) {
					mainFrame = new GameObject ("mainFrame");
					DontDestroyOnLoad (mainFrame);
					if (mainFrame.GetComponent<MainTask> () == null)
						mainFrame.AddComponent<MainTask> ();
				}

				yield break;
			}

			void OnTriggerEnter ()
			{
                DebugTool.Log("DDD");
			}

			void LateUpdate ()
			{
				//Debug.Log("CCC");
				//	StartCoroutine("StartC");
			}

			void Update ()
			{
				//Debug.Log("BBB");


				if (Input.anyKeyDown) {
					if (_paused == false) {
                        DebugTool.LogWarning("Paused!");
						TaskRunner.Instance.PauseManaged ();
						_paused = true;
					} else {
                        DebugTool.LogWarning("Resumed!");
						_paused = false;
						TaskRunner.Instance.ResumeManaged ();
					}
				}
			}

			IEnumerator SaveBundlesInfo (string path, string json)
			{
                DebugTool.Log("JSON=" + json);
				string dir = Application.dataPath + "/" + "ResourcesInfo";
				if (!Directory.Exists (path))
					Directory.CreateDirectory (path);
				string f = dir + "/" + path;
				if (!File.Exists (f))
					File.Create (f);
				#if UNITY_WEBPLAYER
				#else
				//DateTime t = new FileInfo (f).LastWriteTime;
				#endif

				byte[] bytes = System.Text.Encoding.UTF8.GetBytes (json);
				//判断是否与服务器一致

				//先保存原来文件
				//更新资源文件
				//FileS
				//byte[] BUFFER = new byte[1024];
				FileStream fs;
				try {
					fs = new FileStream (f, FileMode.Create, FileAccess.Write, FileShare.None);
					fs.Write (bytes, 0, bytes.Length);
				} catch (CException ex) {
					throw new CException (ex.Message);
				}
				yield return null;
			}

			IEnumerator DoSomethingAsynchonously () //this can be awfully slow, since it is synched with the framerate
			{
				for (i = 0; i < 500; i++)
					yield return i;

                DebugTool.Log("index " + i);
			}

			IEnumerator Print (string i)
			{
                DebugTool.Log(i);
				yield return null;
			}

			IEnumerator WWWDownloadBundlesInfos (string url)
			{
				if (url != null) {
					WWW www = new WWW (url);
					yield return www;
					if (www.error != null) {
						throw new System.Exception ("下载资源列表是发生错误:" + www.error);
						//yield break;
					}
				}
				testBundlesInfo (JSON);
				yield return null;
			}

			IEnumerator WWWTest (string url)
			{
				WWW www = new WWW (url);

				yield return www;

                DebugTool.Log("网页内容： " + www.text);
			}


			/// <summary>
			/// 载入指定模型的脚本
			/// </summary>
			/// <returns>The target script.</returns>
			/// <param name="BundleURL">Bundle UR.</param>
			/// <param name="path">Path.</param>
			/// <param name="go">游戏模型对象GameObject</param>
			/// <param name="version">Version.</param>
			IEnumerator LoadTargetScript (string BundleURL, string path, GameObject go, int version)
			{
	            while (!Caching.ready)
	                yield return null;
				using (WWW www = WWW.LoadFromCacheOrDownload(BundleURL, version)) {
	                yield return www;

				}


	}





			private bool _paused = false;
			public  string  JSON = @"{
	    ""bundles"":[{""id"":00001,""name"":""Test1"",
	    ""type"":0,""alias"":""Test1"",""uri"":""http://..unity3d"",""assetPath"":""/assets/"",""version"":1},
		{""id"":00002,""name"":""Test2"",
				""type"":0,""alias"":""Test1"",""uri"":""http://..unity3d"",""assetPath"":""/assets/"",""version"":1},
		{""id"":00003,""name"":""Test3"",
				""type"":0,""alias"":""Test1"",""uri"":""http://..unity3d"",""assetPath"":""/assets/"",""version"":1},
		{""id"":00004,""name"":""Test4"",
				""type"":0,""alias"":""Test1"",""uri"":""http://..unity3d"",""assetPath"":""/assets/"",""version"":1}]
		}";
			private string BUNDLES_LABEL = "bundles";
			private string BUNDLE_ID_LABEL = "id";
			private string BUNDLE_NAME_LABEL = "name";
			private string BUNDLE_TYPE_LABEL = "type";
			private string BUNDLE_ALIAS_LABEL = "alias";
			private string BUNDLE_PATH_LABEL = "uri";
			private string BUNDLE_ASSETPATH_LABEL = "assetPath";
			private string BUNDLE_VERSION_LABEL = "version";
			/// <summary>
			/// 解析包列表
			/// </summary>
			/// <param name="str">String.</param>
			public  List<PrefabBundleModel> testBundlesInfo (string str)
			{
				List<PrefabBundleModel> list = new List<PrefabBundleModel> ();
				JSONObject json = new JSONObject (str);
				List<JSONObject> bundles = json.GetField (BUNDLES_LABEL).list;
				foreach (JSONObject j in bundles) {
					PrefabBundleModel b = new PrefabBundleModel ();
					b.Id = (long)j.GetField (BUNDLE_ID_LABEL).n;
					b.Name = j.GetField (BUNDLE_NAME_LABEL).str;
					b.URLPath = j.GetField (BUNDLE_PATH_LABEL).str;
					b.Alias = j.GetField (BUNDLE_ALIAS_LABEL).str;

					b.AssetPath = j.GetField (BUNDLE_ASSETPATH_LABEL).str;
					b.Version = (int)j.GetField (BUNDLE_VERSION_LABEL).n;
					///判断包类型
					int _type = (int)j.GetField (BUNDLE_TYPE_LABEL).n;
					switch (_type) {
					case (int)MODEL_TYPE.HUMAN:
						break;
					case (int)MODEL_TYPE.POSSESSION:
						break;
					}
					list.Add (b);

				}
				return list;		
		}
	        /// <summary>
	        /// 载入模型
	        /// </summary>
	        /// <returns>The model.</returns>
	        /// <param name="BundleURL">Bundle UR.</param>
	        /// <param name="version">Version</param>   
	        /// <param name="Params">params[0] AssetName,params[1]type,params[2]version</param>
	        IEnumerator WWWModel(string BundleURL, string AssetName, int version, LoadResourceType type, List<CTuple<string, string, int>> Params)
	        {
                DebugTool.Log("正在读取模型资源，请稍候。");    
	            ///string AssetName = "";
	            //// WWW www = new WWW(BundleURL);
	            ////   yield return www;
	            if (BundleURL.IndexOf("unity3d") > 0)
	            {
	                ////  GameObject go = new GameObject();
	                ////不同平台下StreamingAssets的路径是不同的，这里需要注意一下

	                string PathURL =

	#if UNITY_ANDROID

	 "jar:file://" + Application.dataPath + "!/assets/";

	#elif UNITY_IPHONE

					Application.dataPath + "/Raw/";

	#elif UNITY_STANDALONE_WIN || UNITY_EDITOR

					"file://" + Application.dataPath + "/StreamingAssets/";

	#else
					string.Empty;
	#endif
	                // Wait for the Caching system to be ready
	                while (!Caching.ready)
	                    yield return null;

	                // Load the AssetBundle file from Cache if it exists with the same version or download and store it in the cache
	                using (WWW www = WWW.LoadFromCacheOrDownload(BundleURL, version))
	                {
	                    yield return www;
	                    if (www.error != null)
	                        throw new System.Exception("下载模型时发生错误" + www.error);
	                    AssetBundle bundle = www.assetBundle;
	                    if (AssetName == "")
	                    {
	                        if (bundle.mainAsset != null)
	                            Instantiate(bundle.mainAsset);
	                    }
	                    else
	                    {

	                        //					if(Params!=null&&Params.Count>0){
	                        //
	                        //
	                        //
	                        //
	                        //
	                        //
	                        //					}else{


                            DebugTool.Log("开始读取prefab");

	                        //according to asset name
	                        if (type == LoadResourceType.DEFAULT)
	                        {

	                            Instantiate(bundle.Load(AssetName) as GameObject);

	                        }
	                        else
	                        {
	                            //according to type

	                            Type _type = typeof(GameObject);

	                            switch ((int)type)
	                            {
	                                case (int)LoadResourceType.GAMEOBJECT:
	                                    _type = typeof(GameObject);
	                                    break;


	                                //case (int)LoadResourceType.PREFAB:
	                                //	break;
	                                default:

	                                    break;
	                            }
	                            AssetBundleRequest request = bundle.LoadAsync(AssetName, _type);
	                            yield return request;

	                            //foreach (UnityEngine.Object go2 in bundle.LoadAll()) {
	                            //	Instantiate (go2);
	                            //}
                                DebugTool.Log("Loading game object model");
	                            GameObject obj = request.asset as GameObject;
	                            Instantiate(obj);
	                            // yield return
	                        } 
	                    }
	                    //Instantiate (bundle.Load (AssetName));
	                    // Unload the AssetBundles compressed contents to conserve memory
	                    bundle.Unload(false);

	                    // Debug.Log("www done:" + www.text);
	                } // memory is freed from the web stream (www.Dispose() gets called implicitly)

	            }
	        }
		}

	}